
# include "hoopoe.h"

unsigned int
GetFileForAnalysis
(
LPFileInfo pFileToBeAnalyzed
)
{
	unsigned int retVal = SUCCESS;

	// GET THE HANDLE TO FILE
	pFileToBeAnalyzed->hFile = CreateFileW(pFileToBeAnalyzed->FileName.c_str(), 
			   GENERIC_READ,
			   FILE_SHARE_READ,
			   NULL,
			   OPEN_EXISTING,
			   FILE_ATTRIBUTE_NORMAL,
			   NULL);

	if(pFileToBeAnalyzed->hFile == INVALID_HANDLE_VALUE){
		gLastErrorCode = GetLastError();
		fprintf(stdout, "can not open file :(%ws):%d\n", pFileToBeAnalyzed->FileName.c_str(), GetLastError());
		return FAILURE;
	}

	//Also Get the File Size
	pFileToBeAnalyzed->FileSize = GetFileSize(pFileToBeAnalyzed->hFile, &pFileToBeAnalyzed->FileSizeHigh);
	if(pFileToBeAnalyzed->FileSizeHigh > 0){
		fprintf(stdout, "No Support for large files. :(%ws):%d\n", pFileToBeAnalyzed->FileName.c_str(), GetLastError());
		return FAILURE;
	}
	if(pFileToBeAnalyzed->FileSize == INVALID_FILE_SIZE){
		fprintf(stdout, "Could not get File Size. :(%ws):%d\n", pFileToBeAnalyzed->FileName.c_str(), GetLastError());
		return FAILURE;
	}


	// get file mapping handle
	pFileToBeAnalyzed->hFileMapping = CreateFileMappingW(pFileToBeAnalyzed->hFile,
					  NULL,
					  PAGE_READONLY,
					  0, 0,
					  NULL);
	if(pFileToBeAnalyzed->hFileMapping == NULL)
	{
		CloseHandle(pFileToBeAnalyzed->hFile);
		gLastErrorCode = GetLastError();
		fprintf(stdout, "can not create file mapping :(%ws):%d\n", 
						pFileToBeAnalyzed->FileName.c_str(), GetLastError());
		
		return FAILURE;
	}

	// create a view of file and get a pointer to base of file
	//
	pFileToBeAnalyzed->lpFileBase = MapViewOfFile(pFileToBeAnalyzed->hFileMapping, FILE_MAP_READ, 0, 0, 0);
	
	// return if this call is failed.
	if(pFileToBeAnalyzed->lpFileBase == 0) {
		CloseHandle(pFileToBeAnalyzed->hFileMapping);
		CloseHandle(pFileToBeAnalyzed->hFile);
		fprintf(stdout, "can not map view of file :(%s):%d\n", pFileToBeAnalyzed->FileName.c_str(), GetLastError());
		return FAILURE;
	}

	return retVal;
}

void CloseFile
(
 LPFileInfo pFileToBeAnalyzed
)
{
	if(pFileToBeAnalyzed->hFileMapping != NULL)
		CloseHandle(pFileToBeAnalyzed->hFileMapping);

	if(pFileToBeAnalyzed->hFile != INVALID_HANDLE_VALUE)
		CloseHandle(pFileToBeAnalyzed->hFile);
}